package com.liy.framework.common.logs.appender;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.StackTraceElementProxy;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import com.liy.framework.common.extvo.LogAttributeInfo;
import com.liy.framework.common.logs.LogsAutoConfiguration;
import com.mongodb.BasicDBObject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

@Component
public class MongodbAppender extends UnsynchronizedAppenderBase<ILoggingEvent> implements ApplicationContextAware {
    private Logger log = LoggerFactory.getLogger(MongodbAppender.class);
    public static MongoTemplate mongoTemplate;
    public static String sysId = "_";
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");

    public MongodbAppender() {
    }

    protected void append(ILoggingEvent event) {
        if (mongoTemplate != null) {
            BasicDBObject doc = new BasicDBObject();
            String level = event.getLevel().toString();
            doc.append("sysId", sysId);
            doc.append("level", level);
            StringBuilder sb;
            int i;
            if (event.getLoggerName() != null && !"".equals(event.getLoggerName())) {
                String[] arr = event.getLoggerName().split("\\.");
                sb = new StringBuilder();

                for(i = 0; i < arr.length; ++i) {
                    if (i == arr.length - 1) {
                        sb.append(".");
                        sb.append(arr[i]);
                    } else {
                        if (i != 0) {
                            sb.append(".");
                        }

                        sb.append(arr[i].substring(0, 1));
                    }
                }

                doc.append("logger", sb.toString());
            }

            doc.append("thread", event.getThreadName());
            doc.append("message", event.getFormattedMessage());
            doc.append("timestamp", event.getTimeStamp());
            if (event.getArgumentArray() != null && event.getArgumentArray().length > 0) {
                Object[] var10 = event.getArgumentArray();
                int var12 = var10.length;

                for(i = 0; i < var12; ++i) {
                    Object obj = var10[i];
                    if (obj instanceof LogAttributeInfo) {
                        LogAttributeInfo log = (LogAttributeInfo)obj;
                        doc.append("requestUrl", log.getUrl());
                        doc.append("responseTime", log.getTime());
                    }
                }
            }

            IThrowableProxy proxy = event.getThrowableProxy();
            if (proxy != null) {
                sb = new StringBuilder(proxy.getClassName());
                sb.append(": ").append(proxy.getMessage());
                StackTraceElementProxy[] var15 = proxy.getStackTraceElementProxyArray();
                int var16 = var15.length;

                for(int var18 = 0; var18 < var16; ++var18) {
                    StackTraceElementProxy stack = var15[var18];
                    sb.append(",").append(stack.toString());
                }

                doc.append("exception", sb.toString());
            } else {
                doc.append("exception", "");
            }

            if (event.getCallerData() != null && event.getCallerData().length > 0) {
                StackTraceElement st = event.getCallerData()[0];
                String callerData = String.format("%s.%s:%d", st.getClassName(), st.getMethodName(), st.getLineNumber());
                doc.append("caller", callerData);
            }

            Map<String, String> mdc = event.getMDCPropertyMap();
            if (mdc != null && !mdc.isEmpty()) {
                doc.append("mdc", new BasicDBObject(mdc));
            }

            doc.append("status", "unread");
            mongoTemplate.insert(doc, "RUNLOG_" + this.sdf.format(new Date()));
        }
    }

    public void setApplicationContext(ApplicationContext applicationContext) {
        LogsAutoConfiguration configuration = (LogsAutoConfiguration)applicationContext.getAutowireCapableBeanFactory().getBean(LogsAutoConfiguration.class);
        if (configuration != null) {
            sysId = configuration.getSysId();
        }

        mongoTemplate = (MongoTemplate)applicationContext.getAutowireCapableBeanFactory().getBean(MongoTemplate.class);
        this.log.info("Init MongoTemplate: " + mongoTemplate);
    }
}
